<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 客户需求管理
 *
 * @icon fa fa-circle-o
 */
class CustomerDemand extends Backend
{

    /**
     * CustomerDemand模型对象
     * @var \app\admin\model\CustomerDemand
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\CustomerDemand;

    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if (!empty($params['deliverytime'])) {
            $params['deliverytime'] = strtotime($params['deliverytime']);
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function getProductInfoById()
    {
        try {
            // 1. 参数验证
            $demandId = $this->request->param('id');
            if (empty($demandId)) {
                return json([
                    'code' => 400,
                    'message' => '参数ID不能为空',
                    'data' => null
                ]);
            }

            // 验证ID是否为有效数字
            if (!is_numeric($demandId) || $demandId <= 0) {
                return json([
                    'code' => 400,
                    'message' => '参数ID格式错误',
                    'data' => null
                ]);
            }

            // 2. 查询需求记录
            $demand = $this->model->get($demandId);
            if (empty($demand)) {
                return json([
                    'code' => 404,
                    'message' => '需求记录不存在',
                    'data' => null
                ]);
            }

            // 3. 检查单价是否存在
            if (!isset($demand->unit_price)) {
                return json([
                    'code' => 500,
                    'message' => '需求单价信息缺失',
                    'data' => null
                ]);
            }

            $unit_price = $demand->unit_price;

            // 4. 检查产品关联关系
            if (!method_exists($demand, 'product')) {
                return json([
                    'code' => 500,
                    'message' => '产品关联关系未定义',
                    'data' => null
                ]);
            }

            // 5. 获取产品信息
            $product = $demand->product;
            if (empty($product)) {
                return json([
                    'code' => 404,
                    'message' => '关联的产品信息不存在',
                    'data' => null
                ]);
            }

            // 6. 确保产品信息是数组或对象
            if (is_array($product)) {
                $product['unit_price'] = $unit_price;
            } elseif (is_object($product)) {
                $product->unit_price = $unit_price;
            } else {
                return json([
                    'code' => 500,
                    'message' => '产品数据格式错误',
                    'data' => null
                ]);
            }

            // 7. 成功返回
            return  $product;

        } catch (\Exception $e) {
            // 8. 全局异常捕获
            // 记录日志
            \think\facade\Log::error('获取产品信息失败: ' . $e->getMessage(), [
                'demand_id' => $demandId ?? 'unknown',
                'trace' => $e->getTraceAsString()
            ]);

            return json([
                'code' => 500,
                'message' => '系统错误，请稍后重试',
                'data' => null
            ]);
        }
    }

    public function getCustomerDemandByCustomerId()
    {
        $customerId = $this->request->param('customer_id');
        if (empty($customerId) || !is_numeric($customerId) || $customerId <= 0) {
            return json([
                'code' => 400,
                'message' => '参数customer_id不能为空且必须为正整数',
                'data' => null
            ]);
        }

        try {
            $demands = $this->model->where('customer_id', $customerId)->select();
            return json([
                'code' => 200,
                'message' => '成功',
                'rows' => $demands
            ]);
        } catch (\Exception $e) {
            \think\facade\Log::error('获取客户需求失败: ' . $e->getMessage(), [
                'customer_id' => $customerId,
                'trace' => $e->getTraceAsString()
            ]);

            return json([
                'code' => 500,
                'message' => '系统错误，请稍后重试',
                'data' => null
            ]);
        }
    }

    public function getTableData()
    {
        $demand_ids = $this->request->param('demand_ids');
        if (empty($demand_ids)) {
            return json([
                'code' => 400,
                'message' => '参数demand_ids不能为空',
                'data' => null
            ]);
        }else {
            $idsArray = explode(',', $demand_ids);
            $product_list = [];
            foreach ($idsArray as $id) {
                $demand = $this->model->get($id);
                if ($demand) {
                    $product = $demand->product;
                    if ($product) {
                        $productData = $product->toArray();
                        //附加上demand_id 
                        $productData['demand_id'] = $id;
                        // 把产品数据添加到列表中
                        $product_list[] = $productData;
                    }
                }
            }
            return json([
                'total' => count($product_list),
                'rows' => $product_list
            ]);
        }
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
